const express = require("express");
const router = express.Router();
const RoleModel = require("../../../models/Role");
const middleware_auth = require("../../../middleware/auth");
const assert = require("http-assert");
const { resData } = require("../../../utils/format");
const middleware_permission = require("../../../middleware/permission");
module.exports = app => {
    /**
     * @apiGroup 管理端/角色
     * @api {get} /admin/api/role/menusInRole 获取角色下的菜单
     * @apiParam {String} _id 角色id
     */
    router.get("/menusInRole", async (req, res) => {
        const { _id } = req.query;
        assert(_id, 400, "请传入_id");
        const menuRecord = await RoleModel.find({ _id }).populate("menus");
        assert(menuRecord.length, 400, "该角色不存在");
        const menusInRole = menuRecord[0].menus;
        res.send(resData(menusInRole));
    });
    /**
     * @apiGroup 管理端/角色
     * @api {post} /admin/api/role/addRefMenu 新增角色下的菜单
     * @apiParam {String} roleId 角色id
     * @apiParam {Array} menuIds 菜单id数组
     */
    router.post("/addRefMenu", async (req, res) => {
        const { roleId, menuIds } = req.body;
        assert(roleId, 400, "请传入角色id");
        assert(menuIds, 400, "请传入菜单id");
        assert(menuIds instanceof Array, 400, "menuIds应为数组");
        let roleRecord = await RoleModel.findById(roleId);
        assert(roleRecord, 400, "该角色不存在");
        let newArray = new Array();
        roleRecord.menus.forEach((item, index) => {
            newArray.push(String(item));
        });
        await RoleModel.findByIdAndUpdate(roleId, { menus: new Array(...new Set([...newArray, ...menuIds])) });
        req.session.permissionMenus = null;
        res.send(resData(null, { message: "添加成功" }));
    });
    /**
     * @apiGroup 管理端/角色
     * @api {delete} /admin/api/role/deleteRefMenu 删除角色下的菜单
     * @apiParam {String} roleId 角色id
     * @apiParam {String} menuId 菜单id
     */
    router.delete("/deleteRefMenu", async (req, res) => {
        const { roleId, menuId } = req.body;
        assert(roleId, 400, "请传入roleId");
        assert(menuId, 400, "请传入menuId");
        let roleRecord = await RoleModel.findById(roleId);
        assert(roleRecord, 400, "该角色不存在");
        assert(roleRecord.menus.includes(menuId), 400, "该菜单不在该角色下");
        await RoleModel.findByIdAndUpdate(roleId, { menus: roleRecord.menus.filter(item => String(item) != menuId) });
        req.session.permissionMenus = null;
        res.send(resData(null, { message: "删除成功" }));
    });
    /**
     * @apiGroup 管理端/角色
     * @api {get} /admin/api/role/interfacesInRole 获取角色下的接口
     * @apiParam {String} _id 角色id
     */
    router.get("/interfacesInRole", async (req, res) => {
        const { _id } = req.query;
        assert(_id, 400, "请传入_id");
        const menuRecord = await RoleModel.find({ _id });
        assert(menuRecord.length, 400, "该角色不存在");
        const interfacesInRole = menuRecord[0].interfaces;
        res.send(resData(interfacesInRole));
    });
    /**
     * @apiGroup 管理端/角色
     * @api {post} /admin/api/role/addRefInterface 新增角色下的接口
     * @apiParam {String} roleId 角色id
     * @apiParam {Object} interface 接口对象 {name, interface }
     */
    router.post("/addRefInterface", async (req, res) => {
        const { roleId, interface } = req.body;
        assert(roleId, 400, "请传入角色id");
        assert(interface, 400, "请传入接口对象");
        assert(interface instanceof Object, 400, "interface应为对象");
        let roleRecord = await RoleModel.findById(roleId);
        assert(roleRecord, 400, "该角色不存在");
        if (interface instanceof Object && !interface.length) {
            let canUpdate = roleRecord.interfaces.every(item => item.interface != interface.interface);
            assert(canUpdate, 400, "该接口已存在");
            await RoleModel.findByIdAndUpdate(roleId, {
                interfaces: [...roleRecord.interfaces, { name: interface.name, interface: interface.interface }],
            });
        } else if (interface instanceof Array && interface.length) {
            let addInterfaces = [];
            interface.forEach(item => {
                if (!roleRecord.interfaces.map(item1 => item1.interface).includes(item.interface)) {
                    addInterfaces.push(item);
                }
            });
            await RoleModel.findByIdAndUpdate(roleId, {
                interfaces: [...roleRecord.interfaces, ...addInterfaces.map(item => ({ name: item.name, interface: item.interface }))],
            });
        }
        req.session.permissionInterfaces = null;
        res.send(resData(null, { message: "添加成功" }));
    });
    /**
     * @apiGroup 管理端/角色
     * @api {delete} /admin/api/deleteRefInterface/role 删除角色下的接口
     * @apiParam {String} roleId 角色id
     * @apiParam {Number} interfaceIndex 接口索引
     */
    router.delete("/deleteRefInterface", async (req, res) => {
        const { roleId, interfaceIndex } = req.body;
        assert(roleId, 400, "请传入roleId");
        assert(interfaceIndex != undefined, 400, "请传入interfaceIndex");
        let roleRecord = await RoleModel.findById(roleId);
        assert(roleRecord, 400, "该角色不存在");
        assert(roleRecord.interfaces.length >= interfaceIndex + 1 && interfaceIndex >= 0, 400, "该接口不在该角色下");
        roleRecord.interfaces.splice(interfaceIndex, 1);
        await RoleModel.findByIdAndUpdate(roleId, { interfaces: roleRecord.interfaces });
        req.session.permissionInterfaces = null;
        res.send(resData(null, { message: "删除成功" }));
    });
    app.use("/admin/api/role", middleware_auth(), middleware_permission(), router);
};
